import axios from 'axios'
import { useState, useCallback } from 'react'
import WithRepoBasic from '../../components/with-repo-basic'
import { request } from '../../lib/api'
import SearchUser from '../../components/SearchUser'
import { Avatar, Button, Select, Spin } from 'antd'
import dynamic from 'next/dynamic'
const MdRenderer = dynamic(import('../../components/md-renderer'))

function Label ({ label }) {
  return (
    <>
      <span className="label" style={{ backgroundColor: `#${label.color}` }}>
        {label.name}
      </span>
      <style jsx>{`
        .label {
          display: inline-block;
          line-height: 20px;
          margin-left: 10px;
        }
      `}</style>
    </>
  )
}


function IssueDetail ({ issue }) {
  function goToGithubIssue () {
    window.open(issue.html_url)
  }

  return (
    <div className="root">
      {/* <div dangerouslySetInnerHTML={{ __html: issue.body }} /> */}
      <MdRenderer content={issue.body} />
      <div className="actions">
        <Button onClick={goToGithubIssue}>打开Issue讨论页面</Button>
      </div>
      <style jsx>{`
        .root {
          background-color: #efefef;
          padding: 20px;
        }
        .actions {
          text-align: right;
        }
      `}</style>
    </div>
  )
}


function IssueItem ({ issue }) {
  const [showDetail, setShowDetail] = useState(false)


  const toggleShowDetail = useCallback(
    () => {
      setShowDetail(detail => !detail)
    },
    []
  )
  return (
    <div>
      <div className="issue">
        <Button
          type="primary"
          size="small"
          style={{ position: 'absolute', right: 20, top: 10 }}
          onClick={toggleShowDetail}
        >
          {showDetail ? '隐藏内容' : '显示内容'}
        </Button>
        <div className="avatar">
          <Avatar src={issue.user.avatar_url} shape="square" size={50} />
        </div>
        <div className="main-info">
          <h6>
            <span>{issue.title}</span>
            {issue.labels.map(label => (
              <Label key={label.id} label={label} />
            ))}
          </h6>
          <p className="sub-info">
            <span>Updated at {issue.updated_at}</span>
          </p>
        </div>
        <style jsx>{`
          .issue {
            display: flex;
            position: relative;
            padding: 10px;
          }
          .issue:hover {
            background: #fafafa;
          }
          .issue + .issue {
            border-top: 1px solid #eee;
          }
          .main-info > h6 {
            max-width: 600px;
          }
          .avatar {
            margin-right: 20px;
          }
          .main-info > h6 {
            font-size: 16px;
          }
          .sub-info {
            margin-bottom: 0;
          }
          .sub-info > span + span {
            display: inline-block;
            margin-left: 20px;
            font-size: 12px;
          }
        `}</style>
      </div>
      {showDetail ? <IssueDetail issue={issue} /> : null}
    </div>
  )
}

function makeQuery (creator, state, labels) {
  const creatorStr = creator ? `creator=${creator}` : ''
  const stateStr = state ? `state=${state}` : ''
  let labelStr = ''
  if (labels && labels.length > 0) {
    labelStr = `labels=${labels.join(',')}`
  }

  const arr = []

  if (creatorStr) {
    arr.push(creatorStr)
  }
  if (stateStr) {
    arr.push(stateStr)
  }
  if (labelStr) {
    arr.push(labelStr)
  }

  return `?${arr.join('&')}`
}

const Option = Select.Option
function Issues ({ initialissues, labels, owner, name }) {
  const [creator, setCreator] = useState()
  const [state, setState] = useState()
  const [label, setLabel] = useState([])
  const [issues, setIssues] = useState(initialissues)
  const [fetching, setFetching] = useState(false)
  const handleCreatorChange = useCallback(
    (value) => {
      return setCreator(value)
    }, [])
  const handleStateChange = useCallback(
    (value) => {
      return setState(value)
    }, [])
  const handlabelChange = useCallback(
    (value) => {
      return setLabel(value)
    }, [])
  const handelSearch = async () => {
    setFetching(true)
    const { data: resultIssues } = await request({
      url: `/repos/${owner}/${name}/issues${makeQuery(creator, state, label)}`,
    })
    setIssues(resultIssues)
    setFetching(false)

  }
  return (
    <div className="root">
      <div className="search">
        <SearchUser
          onChange={handleCreatorChange}
          value={creator} />
        <Select
          placeholder="状态"
          style={{ width: 200, marginLeft: 20 }}
          onChange={handleStateChange}
          value={state}
        >
          <Option value="all">all</Option>
          <Option value="open">open</Option>
          <Option value="closed">closed</Option>
        </Select>
        <Select
          mode="multiple"
          placeholder="label"
          style={{ width: 200, marginLeft: 20, marginRight: 20 }}
          onChange={handlabelChange}
          value={label}
        >
          {
            labels.map(label => {
              return <Option value={label.name} key={label.id}>{label.name}</Option>
            })
          }
        </Select>
        <Button type="primary" disabled={fetching} loading={fetching} onClick={handelSearch}>搜索</Button>
        {
          fetching ? (<div className="loading"><Spin /></div>) : (<div>
            {issues.map(issue => (
              <IssueItem issue={issue} key={issue.id} />
            ))}
          </div>)
        }

      </div>
      <style jsx>{`
        }
        .search{
          border: 1px solid #eee;
          border-radius: 5px;
          margin-bottom: 20px;
          margin-top:20px
        }
        .loading{
          height:400px;
          display:flex;
          align-items:center;
          justify-content:center;
        }
      `}</style>
    </div>
  )
}
Issues.getInitialProps = async (ctx) => {

  const { owner, name } = ctx.query

  //const issuesResp = await axios.get(`https://api.github.com/repos/${owner}/${name}/issues`)

  const fetchs = await Promise.all([
    await request({ url: `/repos/${owner}/${name}/issues` }, ctx.req, ctx.res),
    await request({ url: `/repos/${owner}/${name}/labels` }, ctx.req, ctx.res)
  ])

  return {
    initialissues: fetchs[0].data,
    labels: fetchs[1].data,
    owner,
    name
  }

}

export default WithRepoBasic(Issues, 'issues')
